<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="答卷标题" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="类型" clearable style="width: 120px;" class="filter-item">
        <el-option :key="0" label="考试答题" :value="0" />
        <el-option :key="1" label="调研答题" :value="1" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px;" class="filter-item">
        <el-option :key="0" label="未发布" :value="0" />
        <el-option :key="1" label="已发布" :value="1" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        筛选
      </el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      :row-style="{height:'32px'}"
      tooltip-effect="light"
      :default-sort="{prop: 'paperId', order: null}"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" align="center" fixed width="90px" prop="paperId" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.paperId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="试卷标题" align="center" min-width="250px" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="150px" prop="type" sortable="custom">
        <template slot-scope="{row}">
          <el-tag v-if="row.type===0" size="mini" type="primary" effect="plain">考试答题</el-tag>
          <el-tag v-else size="mini" type="success" effect="plain">调研答题</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="150px" prop="status" sortable="custom">
        <template slot-scope="{row}">
          <el-tag v-if="row.status===0" size="mini" type="info">未发布</el-tag>
          <el-tag v-else size="mini" type="success">已发布</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="答题开始时间" align="center" prop="updateTime" sortable="custom" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.startTime }}</span>
          <el-tag v-if="isLaterThanNow(row.startTime)" size="mini" type="info">未开始</el-tag>
          <el-tag v-else size="mini" type="success">已开始</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="答题截止时间" align="center" prop="updateTime" sortable="custom" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.endTime }}</span>
          <el-tag v-if="isLaterThanNow(row.endTime)" size="mini" type="success">未截止</el-tag>
          <el-tag v-else size="mini" type="info">已截止</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="规则奖品" align="center" width="150px">
        <template slot-scope="{row}">
          <el-popover placement="bottom" width="550" trigger="click" title="规则奖品信息">
            <div v-if="row.rules" class="issue-content" v-html="row.rules" />
            <el-button slot="reference" size="mini">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="340px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" plain icon="el-icon-tickets" @click="handleRank(row)">
            排行榜
          </el-button>
          <el-button type="primary" size="mini" @click="goToQuestion(row)">
            详情
          </el-button>
          <el-button type="success" size="mini" :disabled="row.status===1" @click="handleRelease(row.paperId)">
            发布
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row.paperId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showPaperList" />

    <el-dialog title="新增考卷" :visible.sync="dialogPaperInfoVisible" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="paperEditForm" :rules="paperInfoRules" :model="tempPaperInfo" label-width="100px" style="width: 100%" size="small">
        <el-form-item label="id" prop="paperId" hidden>
          <el-input v-model="tempPaperInfo.paperId" style="width: 90%" />
        </el-form-item>
        <el-form-item label="考卷标题" prop="title">
          <el-input v-model="tempPaperInfo.title" style="width: 90%" />
        </el-form-item>
        <el-form-item label="答题类型" prop="title">
          <el-radio-group v-model="tempPaperInfo.type">
            <el-radio :label="0">考试答题</el-radio>
            <el-radio :label="1">调研答题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="tempPaperInfo.startTime" type="datetime" placeholder="选择考试开始时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="tempPaperInfo.endTime" type="datetime" placeholder="选择考试开始时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="奖品规则" prop="rules" style="width: 90%">
          <tinymce v-if="dialogPaperInfoVisible" v-model="tempPaperInfo.rules" :height="200" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPaperInfoVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="editPaperInfo">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="30%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" style="width: 100%">
        <el-form-item label="版块名称" prop="sectionName">
          <el-input v-model="temp.sectionName" style="width: 90%" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="sectionTop">
          <el-switch v-model="temp.sectionTop" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addPaperInfo, showPaperList, deletePaper, releasePaper, getPaperRankBaseInfo, getPaperRankUsers } from '@/api/exam'
import { isLaterThanNow } from '@/utils/date'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'Paper',
  components: { Pagination, Tinymce },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      dialogLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        sortProp: '',
        sortOrder: '',
        title: '',
        type: '',
        status: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      tempPaperInfo: {},
      temp: {
        sectionId: undefined,
        sectionName: '',
        sectionTop: 0
      },
      tempRank: {
        newsId: undefined,
        newsRank: 0
      },
      paperInfoRules: {
        title: [{ required: true, message: '请填写试卷标题', trigger: 'blur' }],
        rules: [{ required: true, message: '请编辑奖品规则', trigger: 'change' }],
        type: [{ required: true, message: '请选择答题类型', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      rules: {
        sectionName: [{ required: true, message: '请填写版块名称', trigger: 'change' }],
        sectionTop: [{ required: true, message: '请设置是否置顶', trigger: 'change' }]
      },
      dialogPaperInfoVisible: false,
      dialogRankVisible: false,
      dialogVisible: false,
      positionList: [
        { key: 0, value: '新闻资讯' },
        { key: 1, value: '信息资讯' },
        { key: 2, value: '维权保障信息' },
        { key: 3, value: '医疗互助信息' },
        { key: 4, value: '职工福利信息' }
      ],
      positionMap: {
        0: '新闻资讯',
        1: '信息资讯',
        2: '维权保障信息',
        3: '医疗互助信息',
        4: '职工福利信息'
      }
    }
  },
  created() {
    this.showPaperList()
  },
  methods: {
    showPaperList() {
      this.listLoading = true
      showPaperList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showPaperList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetDialog() {
      this.temp = {
        sectionId: undefined,
        sectionName: '',
        sectionTop: 0
      }
    },
    resetPaperInfoDialog() {
      this.tempPaperInfo = Object.assign({}, this.paperInfo)
    },
    handleCreate() {
      this.resetPaperInfoDialog()
      this.dialogPaperInfoVisible = true
    },
    editPaperInfo() {
      this.$refs['paperEditForm'].validate((valid) => {
        if (valid) {
          addPaperInfo(this.tempPaperInfo).then(() => {
            this.showPaperList()
            this.dialogPaperInfoVisible = false
            this.$notify({
              title: 'Success',
              message: '新增考卷成功，请进入详情页完善题目信息',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.$router.push({
        name: 'ArticleEdit',
        params: {
          id: row.newsId
        }
      })
    },
    toggleUp(newsId) {
      toggleDisplay({ newsId: newsId, newsDisplay: 1 }).then(() => {
        this.showPaperList()
        this.$notify({
          title: 'Success',
          message: '文章展示成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    toggleDown(newsId) {
      toggleDisplay({ newsId: newsId, newsDisplay: 0 }).then(() => {
        this.showPaperList()
        this.$notify({
          title: 'Success',
          message: '文章撤下成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    resetRankDialog() {
      this.tempRank = {
        newsId: undefined,
        newsRank: 0
      }
    },
    handleRank(row) {
      this.$router.push({
        name: 'ExamRank',
        params: {
          paperId: row.paperId
        }
      })
    },
    handleDelete(paperId) {
      this.$confirm('此操作将不可逆地删除该考卷，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePaper(paperId).then(() => {
          this.showPaperList()
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleRelease(paperId) {
      this.$confirm('此操作将发布该考卷，发布后将无法再对其进行修改，是否继续?', '提示', {
        confirmButtonText: '确认发布',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        releasePaper(paperId).then(() => {
          this.showPaperList()
          this.$notify({
            title: 'Success',
            message: '发布成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    goToQuestion(row) {
      this.$router.push({
        name: 'ExamQuestion',
        params: {
          paperId: row.paperId
        }
      })
    },
    isLaterThanNow(date) {
      return isLaterThanNow(date)
    }
  }
}
</script>

<style scoped>
  .issue-content {
    font-size: 18px;
    line-height: 31px;
  }
</style>
